import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Calendar from '../views/Calendar.vue'
import Notification from '../views/Notification.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/Home',
    meta: { requiresAuth: true },
    component: Home
  },
  {
    path: '/Calendar',
    component: Calendar
  },
  {
    path: '/Notification',
    component: Notification
  },
  {
    path: '/Login',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ '../views/Login.vue')
  },
  {
    path: '/',
    redirect: '/Home'
  },
  {
    path: '*',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = new VueRouter({
  routes
})

// 导航被触发。
// 在失活的组件里调用离开守卫。
// 调用全局的 beforeEach 守卫。
// 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
// 在路由配置里调用 beforeEnter。
// 解析异步路由组件。
// 在被激活的组件里调用 beforeRouteEnter。
// 调用全局的 beforeResolve 守卫 (2.5+)。
// 导航被确认。
// 调用全局的 afterEach 钩子。
// 触发 DOM 更新。
// 用创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数。
router.beforeEach((to, from, next) => {
  console.log(to)
  const login = sessionStorage.getItem('login')
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!login) {
      next({
        path: '/Login'
      })
    } else {
      next()
    }

    if (to.path === '/Login') {
      if (login) {
        next({
          path: '/'
        })
      }
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

export default router
